<?php

/**
 * Created by PhpStorm.
 *
 * @author Tian.Yuxing
 * @email tianyuxing@sciall.org.cn
 * Date: 2025/9/27
 * Time: 09:49
 */

namespace Modules\DataCheck\Services;

use Catch\Exceptions\FailedException;
use Modules\DataCheck\Jobs\SourceFileImportJob;
use Modules\DataCheck\Models\DcTaskSourceFile;

/**
 * Modules\DataCheck\Services TaskService.
 */
class TaskService
{
    /**
     * 创建或查找源文件记录
     *
     * @param string $sourceFilePath
     * @return DcTaskSourceFile
     */
    public function createSourceFile(int $operatorUid, string $sourceFileName,string $sourceFilePath): array
    {
        //判断文件是否真实存在
        $realPath = storage_path($sourceFilePath);
        if (!file_exists($realPath)) {
            throw new FailedException('目标文件不存在');
        }
        // 从文件路径中提取文件名
        $data = [
            'file_name'      => $sourceFileName,
            'created_user_id'=> $operatorUid,
            'file_path'      => $sourceFilePath,
            'file_state'     => 1, // 1表示正常状态
            'remark'         => '系统自动创建',
            'last_used_time' => time(),
        ];
        $sourceFileId = (new DcTaskSourceFile())->storeBy($data);
        if (empty($sourceFileId)) {
            throw new FailedException('目标文件创建失败');
        }
        //查询任务
        $sourceTask = DcTaskSourceFile::query()->find($sourceFileId);
        SourceFileImportJob::dispatch($sourceTask)->onQueue('source-file-import');
        return ['source_file_id' => $sourceFileId, 'source_file' => $sourceFilePath];
    }
}
